package com.wen.system.shiro.filter;

import com.wen.common.enums.CodeEnum;
import com.wen.common.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限验证过滤器，验证用户是否有所需权限，如果没有，不再进行登录验证。响应JSON
 * <p>
 * @author devin <devinlive@163.com>
 * @version 1.0
 * @since 2023/7/23 18:47
 */
@Slf4j
@Component
public class CustomRolesAuthorizationFilter extends RolesAuthorizationFilter {

/*    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        
        // 检查用户是否具备所需角色
        if (mappedValue != null) {
            String[] rolesArray = (String[]) mappedValue;
            if (rolesArray.length == 1) {
                return subject.hasRole(rolesArray[0]);
            } else {
                return subject.hasAllRoles(Arrays.asList(rolesArray));
            }
        }

        // 如果没有指定角色要求，则默认允许访问
        return true;
    }*/

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        log.info("权限验证失败，重定向到登录页面");
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        ResponseResult.printResult(httpServletResponse, ResponseResult.error(CodeEnum.USER_NOT_LOGGED_IN));
        return false;
    }

}